<template>
  <div>
    <h2>购物车列表如下：</h2>
    <table class="table table-bordered table-hover">
      <thead>
        <tr>
          <th>
            全选/反选:<input
              type="checkbox"
              @change="checkAll"
              v-model="allStatus"
            />
          </th>
          <th>商品名称</th>
          <th>商品图片</th>
          <th>商品单价</th>
          <th>商品数量</th>
          <th>商品总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in cartList" :key="index">
          <td>
            <input type="checkbox" v-model="item.status" @change="changeOne" />
          </td>
          <td>{{ item.name }}</td>
          <td>
            <img :src="item.img" alt="" />
          </td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="item.num--" :disabled="item.num < 2">-</button>
            {{ item.num }}
            <button @click="item.num++" :disabled="item.num > 9">+</button>
          </td>
          <td>{{ (item.num * item.price).toFixed(2) }}</td>
          <td>
            <button
              type="button"
              class="btn"
              @click="cartList.splice(index, 1)"
            >
              删除
            </button>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>总计：</td>
          <td colspan="6">
            支付金额：{{ jisuan.money }}---购买数量：{{ jisuan.number }}
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
// 引入操作仓库的助手函数
import { mapGetters } from "vuex";
export default {
  name: "cartIndex",
  data() {
    return {
      allStatus: false,
    };
  },
  computed: {
    ...mapGetters(["cartList"]),
    jisuan() {
      // 1.计算用户选中的商品数量(number)和支付金额(money) //{money:0,number:0}
      let count = this.cartList.reduce(
        (prev, item, index) => {
          console.log("走计算属性了");
          if (item.status) {
            prev.money += parseFloat(item.price) * parseInt(item.num);
            prev.number += parseInt(item.num);
          }
          return prev;
        },
        { money: 0, number: 0 }
      );
      return count;
    },
  },
  mounted() {},
  methods: {
    //  单选
    changeOne() {
      // 1.同步自身的状态（双向绑定不需要单独处理）
      // 2.同步全选的状态  every:只要有一个是false就返回false 全为真才返回true
      this.allStatus = this.cartList.every((item) => item.status);
      // 3.同步下数据仓库中的数据状态
      this.$store.dispatch("addCart", this.cartList);
    },
    checkAll() {
      this.cartList.forEach((item) => {
        item.status = this.allStatus;
      });
    },
  },
};
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
.btn {
  width: 100px;
  height: 40px;
  background-color: #d9534f;
  /* outline: none; */
  border: 0;
  border-radius: 5px;
  color: white;
}
</style>
